package ynu.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.mapper.IOrdersMapper;
import ynu.edu.po.Cart;
import ynu.edu.po.OrderDetailet;
import ynu.edu.po.Orders;
import ynu.edu.service.ICartService;
import ynu.edu.service.IOrderDetailetService;
import ynu.edu.service.IOrdersService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements IOrdersService {
    @Resource
    private IOrdersMapper ordersMapper;
    @Resource
    private IOrderDetailetService orderDetailetService;
    @Resource
    private ICartService cartService;

    @Override
    @Transactional
    public int createOrders(Orders orders) {
        try {
            // 查询当前用户购物车中当前商家的所有食品
            Cart cart = Cart.builder()
                    .userId(orders.getUserId())
                    .businessId(orders.getBusinessId())
                    .build();
            List<Cart> cartList = cartService.listCart(cart);

            // 创建订单（返回生成的订单编号）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orders.setOrderDate(sdf.format(new Date()));
            saveOrder(orders);
            int orderId = orders.getOrderId();

            // 批量添加订单明细
            List<OrderDetailet> list = new ArrayList<>();
            for (Cart c : cartList) {
                OrderDetailet od = OrderDetailet.builder()
                        .orderId(orderId)
                        .foodId(c.getFoodId())
                        .quantity(c.getQuantity())
                        .build();
                list.add(od);
            }
            orderDetailetService.saveOrderDetailetBatch(list);

            // 从购物车表中删除相关食品信息
            cartService.removeCart(cart);

            return orderId;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create orders", e);
        }
    }

    @Override
    public boolean saveOrder(Orders orders) {
        return ordersMapper.insert(orders) > 0;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.selectById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId).orderByAsc("orderId");
        return ordersMapper.selectList(queryWrapper);
    }
}
